import re

import allure
import jsonpath
import requests

from common.logger_util import LoggerUtil
from utils.yaml_util import write_extract_yaml

logger = LoggerUtil().get_logger()


class RequestUtil:

    @allure.step("发送接口请求")
    def send_request(self, **kwargs):
        res = requests.request(**kwargs)
        return res

    def jsonpath_extract(self, res, value):
        data = jsonpath.jsonpath(res, value)
        return data[0]

    def re_extract(self, res, value):
        if "(.*?)" in value or "(.+?)" in value:
            re_value = re.findall(value, res.text)
            if len(re_value) == 0:
                logger.error("正则没有提取到任何值")
            elif len(re_value) == 1:
                return re_value[0]
            else:
                return re_value

    @allure.step("提取数据")
    def data_extract(self, res, ex_value):
        for key, value in ex_value.items():
            if "(.*?)" in value or "(.+?)" in value:
                re_value = self.re_extract(res,value)
                logger.info("提取的数据%s: %s" % (key, re_value))
                write_extract_yaml({key: re_value})
                re_value = re.findall(value, res.text)
                # if len(re_value) == 0:
                #     logger.error("正则没有提取到任何值")
                # elif len(re_value) == 1:
                #     write_extract_yaml({key: re_value[0]})
                #     logger.info("提取的数据%s: %s" % (key, re_value[0]))
                # else:
                #     write_extract_yaml({key: re_value})
                #     logger.info("提取的数据%s: %s" % (key, re_value))

            elif "$." in value:
                json_value = self.jsonpath_extract(res.json(), value)
                write_extract_yaml({key: json_value})
                logger.info("提取的数据%s: %s" % (key, json_value))
            else:
                continue
